<!-- 矢量建筑贴图模式 -->
<template>
  <div class="model-post">
    位置：<input type="text" :value="postion"/>
  </div>
</template>

<script setup>
import * as d3 from 'd3-geo'
import * as turf from '@turf/turf'
import api from '../../api/geoserver'
import { THREE } from 'threebox-plugin'
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'

const map = getCurrentInstance().proxy.$root.$map,
  path = import.meta.env.VITE_APP_PATH

const postion = ref('')
const obj = reactive({
  name: 'a',
  id: '234353'
})
const switchCenter = [115.61602530954485, 34.432852118706904]
// 墨卡托投影转换
const projection = d3
  .geoMercator()
  .center(switchCenter)
  .scale(5600000)
  .translate([0, 0])

let molayersData, schoolInfo

onMounted(() => {
  console.log('分模块中')
  // loadLayerJson()
})

// 加载配置文件中图层信息
async function loadLayerJson() {
  const parameter = {
    service: 'WFS',
    version: '1.0.0',
    request: 'GetFeature',
    maxFeatures: '10000',
    outputFormat: 'application/json',
    typeName: 'zzdx:building_simple'
  }
  const data = await api.getLayerData('zzdx', parameter).catch((err) => console.log(err))

  // molayersData = layerJson.data
  setTimeout(() => {
    addChartletLayer(data.features)
  }, 100)
  // console.log('图层信息', data)
  // createChartletBuildMap(data.features)
}

// 根据配置信息加模型
async function addChartletLayer(features) {

  map.addLayer({
    id: 'sqsfchartlet_layer',
    type: 'custom',
    renderingMode: '3d',
    onAdd: function (map, mbxContext) {
      // console.log('tb', tb)
      // const sphere = tb.sphere({color: 'red', material: 'MeshToonMaterial'})
      //   .setCoords(switchCenter)
      // sphere.addEventListener('ObjectMouseOver', onObjectMouseOver, false)
      // sphere.addEventListener('ObjectMouseOut', onObjectMouseOut, false)
      // add sphere to the scene
      // tb.add(sphere)
      addBuildings(features)
    },
    render: function (gl, matrix) {
      tb.update()
    }
  })
  // 将模型图层位置调整到建筑图层前
  // console.log('schoolInfo', schoolInfo)
  // schoolInfo.layers.some((layer) => {
  //   if(layer.name === '校内建筑') {
  //     map.moveLayer(schoolInfo.modelLayerid, layer.layerId)
  //     return true
  //   }
  // })
}

function addBuildings(data) {
  data.forEach((b) => {
    if(b.geometry) {
      if(b.geometry.coordinates) {
        // console.log('coordinates', b.geometry.coordinates)
        if(b.geometry.coordinates) {
          const polygon = turf.polygon(b.geometry.coordinates)
          const center = turf.centerOfMass(polygon).geometry.coordinates
          const texture = new THREE.TextureLoader().load(path + 'images/material/floors.png')
          texture.wrapS = texture.wrapT = THREE.RepeatWrapping
          texture.repeat.set(2, parseInt(b.properties.height / 5)) //重复产生N个相同贴图 产生N行
          texture.offset.set(0, 0.5)
          const material1 = new THREE.MeshBasicMaterial({
            // color: '#999999',
            // transparent: true,
            // opacity: 0.6,
            map: texture
          })
          const material = new THREE.MeshBasicMaterial({
            color: b.properties.color,
            transparent: true,
            opacity: 0.9
          })
          material.color.offsetHSL(0, 0, -0.1)
          const extrusion = tb.extrusion({
            coordinates: b.geometry.coordinates,
            geometryOptions: { curveSegments: 1, bevelEnabled: false, depth: b.properties.height / 50 },
            materials: [material, material1]
          })
          // extrusion.addTooltip(b.properties.tooltip, true)
          extrusion.setCoords([center[0], center[1], 0])
          extrusion.addEventListener('SelectedChange',(e) => {
            console.log('点击对象===================》', e)
            postion.value = e.detail.coordinates.toString()
          })
          extrusion.addEventListener('ObjectDragged',(e) => {
            console.log('拖拽对象===================》', e)
            postion.value = e.detail.draggedObject.coordinates.toString()
          })
          tb.add(extrusion)
        }
      }
    }else{
      console.log('coordinates', b)
    }
  })
  // const center = obj1.geometry.coordinates[0][0]
  // const s = tb.projectedUnitsPerMeter(center[1])


  // })
}


function createChartletBuildMap(elem) {
  // 建一个空对象存放对象
  // const map = new THREE.Object3D()
  console.log('elem', elem)

  // chinaJson.forEach((elem) => {
  // 定一个建筑3D对象
  const province = new THREE.Object3D()
  // 每个的 坐标 数组
  const coordinates = elem?.geometry?.coordinates

  // 循环坐标数组
  if(!coordinates || coordinates.length > 1) {
    return
  }
  // console.log('coordinates===>', coordinates)
  coordinates.forEach((multiPolygon) => {

    multiPolygon.forEach((polygon) => {
      const shape = new THREE.Shape()
      const lineMaterial = new THREE.LineBasicMaterial({ color: 'white' })
      const lineGeometry = new THREE.BufferGeometry()
      const linePoints = []
      for (let i = 0; i < polygon.length; i++) {
        const [x, y] = projection(polygon[i])
        if (i === 0) {
          shape.moveTo(x, -y)
        }
        shape.lineTo(x, -y)
        linePoints.push(new THREE.Vector3(x, -y, 5.02))
      }
      lineGeometry.setFromPoints(linePoints)

      const extrudeSettings = {
        depth: 5,
        bevelEnabled: false
      }

      const geometry = new THREE.ExtrudeGeometry(shape, extrudeSettings)
      const material = new THREE.MeshBasicMaterial({
        color: '#12619f',
        transparent: true,
        opacity: 1
      })
      const material1 = new THREE.MeshBasicMaterial({
        color: '#3991d3',
        transparent: true,
        opacity: 0.6
      })
      const mesh = new THREE.Mesh(geometry, [material, material1])
      const line = new THREE.Line(lineGeometry, lineMaterial)
      mesh.rotateX(29.84)
      line.rotateX(29.84)
      mesh.translateZ(1 * 6)
      line.translateZ(1 * 6)

      province.add(mesh)
      // province.add(line)
    })
  })
  // 将geo的属性放到省份模型中
  province.properties = elem?.properties
  // if (elem.properties.contorid) {
  //   const [x, y] = projection(elem.properties.contorid)
  //   province.properties._centroid = [x, y]
  // }
  // map.add(province)
  // })
  // console.log('map========', map)
  return province
}

defineExpose({
  loadLayerJson
})

</script>

<style lang='scss' scoped>
.model-post{
  position: fixed;
  top: 150px;
  right: 10px;
  width: 220px;
  height: 100px;
  background-color: #fff;
}
</style>
